#!/usr/bin/python
# _*_ coding:utf-8 _*_
import numpy as np
import cv2


def rgb2hsv(b, g, r):
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx-mn
    if mx == mn:
        h = 0
    elif mx == r and g >= b:
        h = 60 * ((g - b) / df) + 0
    elif mx == r and g < b:
        h = 60 * ((g-b)/df) + 360
    elif mx == g:
        h = 60 * ((b-r)/df) + 120
    elif mx == b:
        h = 60 * ((r-g)/df) + 240
    if mx == 0:
        s = 0
    else:
        s = df/mx
    v = mx
    return h, s, v

scale = 0.5
area_min_y = 350 * scale
area_max_y = 1160 * scale

img = cv2.imread("./temp/124105.png")
img = cv2.resize(img, (0, 0), fx=scale, fy=scale)
rows, cols, channels = img.shape

# 阈值化处理
(T, thresh) = cv2.threshold(img, 200, 255, cv2.THRESH_TOZERO)
# cv2.imshow("Threshold Binary", thresh)

erode = cv2.erode(thresh, None, iterations=3)
# cv2.imshow("erode", erode)
# 膨胀
dilate = cv2.dilate(erode, None, iterations=3)
cv2.imshow("dilate", dilate)

# 获取轮廓
img_gray = cv2.cvtColor(dilate, cv2.COLOR_BGR2GRAY)
image, contours, hierarchy = cv2.findContours(img_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

touchs = []
for i in range(0, len(contours)):
    cnt = contours[i]
    x, y, w, h = cv2.boundingRect(cnt)
    if y < area_min_y or y > area_max_y:
        continue
    # 计算该轮廓的面积，面积小的都筛选掉
    if cv2.contourArea(cnt) < 500:
        continue
    center = (x + int(w / 2), y + int(h / 2))
    touchs.append({'x': x, 'y': y, 'w': w, 'h': h, 'center': center})

img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
for t in touchs:
    # 画中心点
    cv2.circle(img, t['center'], 5, (0, 0, 0), -1)
    cv2.rectangle(img, (t['x'], t['y']), (t['x'] + t['w'], t['y'] + t['h']), (153, 153, 0), 5)
    # print(t['center'])

    x = t['x']
    y = t['y']
    w = t['w']
    h = t['h']
    total = 0
    for i in range(0, 10):
        for j in range(0, 10):
            xx = x + int(i / 10 * w)
            yy = y + int(j / 10 * h)
            if xx < rows and yy < cols:
                temp = img_hsv[xx, yy]
                h,s,v = rgb2hsv(temp[0],temp[1],temp[2])
                if h > 50 :
                    total = int(total + h)
    print(total)

cv2.imshow("img", img)

cv2.waitKey(0)
